package com.stylefeng.guns.core.common.constant.factory;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.common.constant.cache.Cache;
import com.stylefeng.guns.core.common.constant.cache.CacheKey;
import com.stylefeng.guns.core.common.constant.state.ManagerStatus;
import com.stylefeng.guns.core.common.constant.state.MenuStatus;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.support.StrKit;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.SpringContextHolder;
import com.stylefeng.guns.core.util.ToolUtil;
import com.stylefeng.guns.modular.netcar.dao.OrderTypeMapper;
import com.stylefeng.guns.modular.netcar.model.OrderType;
import com.stylefeng.guns.modular.system.dao.*;
import com.stylefeng.guns.modular.system.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 常量的生产工厂
 *
 * @author fengshuonan
 * @date 2017年2月13日 下午10:55:21
 */
@Component
@DependsOn("springContextHolder")
public class ConstantFactory implements IConstantFactory {
  private RoleCwMapper roleCwMapper = SpringContextHolder.getBean(RoleCwMapper.class);
  private UserCwMapper userCwMapper = SpringContextHolder.getBean(UserCwMapper.class);
  private RoleMapper roleMapper = SpringContextHolder.getBean(RoleMapper.class);
  private DeptMapper deptMapper = SpringContextHolder.getBean(DeptMapper.class);
  private DictMapper dictMapper = SpringContextHolder.getBean(DictMapper.class);
  private SysDictMapper sysDictMapper = SpringContextHolder.getBean(SysDictMapper.class);
  private UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
  private MenuMapper menuMapper = SpringContextHolder.getBean(MenuMapper.class);
  private NoticeMapper noticeMapper = SpringContextHolder.getBean(NoticeMapper.class);
  private OrgMapper orgMapper = SpringContextHolder.getBean(OrgMapper.class);
  private FunctionMapper functionMapper = SpringContextHolder.getBean(FunctionMapper.class);
  private PostMapper postMapper=SpringContextHolder.getBean(PostMapper.class);
  private OrderTypeMapper orderTypeMapper=SpringContextHolder.getBean(OrderTypeMapper.class);
  private OrgcategoryRoleMapper orgcategoryRoleMapper=SpringContextHolder.getBean(OrgcategoryRoleMapper.class);
  public static IConstantFactory me() {
    return SpringContextHolder.getBean("constantFactory");
  }

  /**
   * 根据用户id获取用户名称
   *
   * @author stylefeng @Date 2017/5/9 23:41
   */
  @Override
  public String getUserNameById(Integer userId) {
    User user = userMapper.selectById(userId);
    if (user != null) {
      return user.getName();
    } else {
      return "--";
    }
  }

  /**
   * 根据用户id获取用户账号
   *
   * @author stylefeng
   * @date 2017年5月16日21:55:371
   */
  @Override
  public String getUserAccountById(Integer userId) {
    User user = userMapper.selectById(userId);
    if (user != null) {
      return user.getAccount();
    } else {
      return "--";
    }
  }

  /** 通过角色ids获取角色名称 */
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.ROLES_NAME + "'+#roleIds")
  public String getRoleName(String roleIds) {
    String[] roles = StringUtils.split(roleIds,",");
    StringBuilder sb = new StringBuilder();
    for (String role : roles) {
      RoleCw roleObj = roleCwMapper.selectById(role);
        OrgcategoryRole oRloe=null;
      if(roleObj==null){//角色不存在 查看模板角色
           oRloe=this.orgcategoryRoleMapper.selectById(role);
      }
      if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getSrName())) {
        sb.append(roleObj.getSrName()).append(",");
      }else{
        if(oRloe!=null)
          sb.append(oRloe.getSorName()).append(",");
      }
    }
    return StrKit.removeSuffix(sb.toString(), ",");
  }
  
  @CachePut(value = Cache.CONSTANT, key = "'" + CacheKey.OT_NAME + "'+#otType+'_'+#otCode")
  public String getOrderTypeByOtCoe(String otType,String otCode){
      if(ToolUtil.isOneEmpty(otType,otCode)){
          return "-";
      }
      Wrapper<OrderType> wrapper= new EntityWrapper<>();
      wrapper.eq("ot_type", otType).and();
      wrapper.eq("ot_code", otCode);
      wrapper.orderBy("ot_id");
      List<OrderType> list= orderTypeMapper.selectList(wrapper);
      Optional<OrderType> result =list.parallelStream().filter(obj -> StringUtils.isNotEmpty(obj.getOtName())).findFirst();
      return result.get().getOtName();
  
  }
  
  /** 通过角色id获取角色名称 */
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_NAME + "'+#roleId")
  public String getSingleRoleName(String roleId,Integer type) {
    if (StringUtils.equals("0",roleId)) {
      return "--";
    }
    if (type.equals(0)){
      Role roleObj = roleMapper.selectById(roleId);
        if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
            return roleObj.getName();
        }
    } else {
      RoleCw roleCwObj = roleCwMapper.selectById(roleId);
        if (ToolUtil.isNotEmpty(roleCwObj) && ToolUtil.isNotEmpty(roleCwObj.getSrName())) {
        return roleCwObj.getSrName();
        }else{
         OrgcategoryRole  orgcategoryRole= this.orgcategoryRoleMapper.selectById(roleId);
         if (orgcategoryRole!=null&&StringUtils.isNoneEmpty(orgcategoryRole.getSorName())){
             return orgcategoryRole.getSorName();
         }
        }
      }
   
    return "";
  }

  /** 通过角色id获取角色英文名称 */
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.SINGLE_ROLE_TIP + "'+#roleId")
  public String getSingleRoleTip(String roleId) {
    if (StringUtils.equals("0",roleId)) {
      return "--";
    }
    Role roleObj = roleMapper.selectById(roleId);
    if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
      return roleObj.getTips();
    }
    return "";
  }

  /** 获取部门名称 */
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.DEPT_NAME + "'+#deptId")
  public String getDeptName(Integer deptId) {
    Dept dept = deptMapper.selectById(deptId);
    if (ToolUtil.isNotEmpty(dept) && ToolUtil.isNotEmpty(dept.getFullname())) {
      return dept.getFullname();
    }
    return "";
  }

  /**
   * 获取组织机构名称
   *
   * @param soId
   */
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.ORG_NAME + "'+#soId")
  public String getOrgName(Integer soId) {
    Org org = orgMapper.selectById(soId);
    if (ToolUtil.isNotEmpty(org) && ToolUtil.isNotEmpty(org.getSoName())) {
      return org.getSoName();
    }
    return "";
  }
  
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.POST_NAME + "'+#spId")
  public String getPostName(Integer spId) {
    Post p = postMapper.selectById(spId);
    if (ToolUtil.isNotEmpty(p) && ToolUtil.isNotEmpty(p.getSpName())) {
      return p.getSpName();
    }
    return "";
  }
  
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.DICT_NAME + "'+'_'+#p0+'_'+#p1")
  public String getDictNameByCode(String pCode, String code) {
   SysDict dict=new SysDict();
   dict.setCode(pCode);
   SysDict sysDict=this.sysDictMapper.selectOne(dict);
   if(sysDict!=null){
    Wrapper<SysDict> wrapper=new EntityWrapper<>();
    int id=sysDict.getId();
    wrapper.eq("pid", id);
    List<SysDict> list=this.sysDictMapper.selectList(wrapper);
    if (list!=null && !list.isEmpty()){
        List<SysDict> temp= list.stream().filter(s->StringUtils.equals(code, s.getCode())).collect(Collectors.toList());
        if(!temp.isEmpty()){
            SysDict sysDict1=temp.get(0);
            return sysDict1.getName();
        }
        
    }
   }
    return "";
  }
  
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.PPOST_NAME + "'+#sppId")
  public String getPostName(String sppId) {
      StringBuilder names=new StringBuilder();
      String[] str= StringUtils.split(sppId,",");
      if(str!=null && str.length>0){
      int[] ia= Arrays.stream(str).mapToInt(Integer::valueOf).toArray();
        if (ia.length > 0) {
            for (int spId : ia) {
            Post p = postMapper.selectById(spId);
                if(ToolUtil.isNotEmpty(p) && ToolUtil.isNotEmpty(p.getSpName())) {
                   names.append(p.getSpName()).append(",");
        }
      }
    }
    }
    return StrUtil.removeSuffix(names.toString(),",");
  }
  
  @Override
  @Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.FUNCTION_NAME + "'+#sfPcode")
  public String getFunctionName(String sfPcode) {
    Function f = new Function();
    f.setSfCode(sfPcode);
    Function function = functionMapper.selectOne(f);
    if (ToolUtil.isEmpty(function)) return "";
    return function.getSfName();
  }

  /** 获取菜单的名称们(多个) */
  @Override
  public String getMenuNames(String menuIds) {
    Integer[] menus = Convert.toIntArray(menuIds);
    StringBuilder sb = new StringBuilder();
    for (int menu : menus) {
      Menu menuObj = menuMapper.selectById(menu);
      if (ToolUtil.isNotEmpty(menuObj) && ToolUtil.isNotEmpty(menuObj.getName())) {
        sb.append(menuObj.getName()).append(",");
      }
    }
    return StrKit.removeSuffix(sb.toString(), ",");
  }

  /** 获取菜单名称 */
  @Override
  public String getMenuName(Long menuId) {
    if (ToolUtil.isEmpty(menuId)) {
      return "";
    } else {
      Menu menu = menuMapper.selectById(menuId);
      if (menu == null) {
        return "";
      } else {
        return menu.getName();
      }
    }
  }

  /** 获取菜单名称通过编号 */
  @Override
  public String getMenuNameByCode(String code) {
    if (ToolUtil.isEmpty(code)) {
      return "";
    } else {
      Menu param = new Menu();
      param.setCode(code);
      Menu menu = menuMapper.selectOne(param);
      if (menu == null) {
        return "";
      } else {
        return menu.getName();
      }
    }
  }

  /** 获取字典名称 */
  @Override
  public String getDictName(Integer dictId) {
    if (ToolUtil.isEmpty(dictId)) {
      return "";
    } else {
      Dict dict = dictMapper.selectById(dictId);
      if (dict == null) {
        return "";
      } else {
        return dict.getName();
      }
    }
  }

  /** 获取通知标题 */
  @Override
  public String getNoticeTitle(Integer dictId) {
    if (ToolUtil.isEmpty(dictId)) {
      return "";
    } else {
      Notice notice = noticeMapper.selectById(dictId);
      if (notice == null) {
        return "";
      } else {
        return notice.getTitle();
      }
    }
  }

  /** 根据字典名称和字典中的值获取对应的名称 */
  @Override
  public String getDictsByName(String name, Integer val) {
    Dict temp = new Dict();
    temp.setName(name);
    Dict dict = dictMapper.selectOne(temp);
    if (dict == null) {
      return "";
    } else {
      Wrapper<Dict> wrapper = new EntityWrapper<>();
      wrapper = wrapper.eq("pid", dict.getId());
      List<Dict> dicts = dictMapper.selectList(wrapper);
      for (Dict item : dicts) {
        if (item.getNum() != null && item.getNum().equals(val)) {
          return item.getName();
        }
      }
      return "";
    }
  }

  /** 获取性别名称 */
  @Override
  public String getSexName(Integer sex) {
    return getDictsByName("性别", sex);
  }

  /** 获取用户登录状态 */
  @Override
  public String getStatusName(Integer status) {
    return ManagerStatus.valueOf(status);
  }

  /** 获取菜单状态 */
  @Override
  public String getMenuStatusName(Integer status) {
    return MenuStatus.valueOf(status);
  }

  /** 查询字典 */
  @Override
  public List<Dict> findInDict(Integer id) {
    if (ToolUtil.isEmpty(id)) {
      return null;
    } else {
      EntityWrapper<Dict> wrapper = new EntityWrapper<>();
      List<Dict> dicts = dictMapper.selectList(wrapper.eq("pid", id));
      if (dicts == null || dicts.size() == 0) {
        return null;
      } else {
        return dicts;
      }
    }
  }

  /** 查询字典 按照字典名称获取所有子类字典列表 */
  @Override
  public List<Dict> findInDictByCode(String code) {
    if (ToolUtil.isEmpty(code)) {
      return null;
    } else {
      List<Dict> dicts = dictMapper.selectByParentCode(code);
      if (dicts == null || dicts.size() == 0) {
        return null;
      } else {
        return dicts;
      }
    }
  }

  /** 获取被缓存的对象(用户删除业务) */
  @Override
  public String getCacheObject(String para) {
    return LogObjectHolder.me().get().toString();
  }

  /** 获取子部门id */
  @Override
  public List<Integer> getSubDeptId(Integer deptid) {
    Wrapper<Dept> wrapper = new EntityWrapper<>();
    wrapper = wrapper.like("pids", "%[" + deptid + "]%");
    List<Dept> depts = this.deptMapper.selectList(wrapper);

    ArrayList<Integer> deptids = new ArrayList<>();

    if (depts != null && depts.size() > 0) {
      for (Dept dept : depts) {
        deptids.add(dept.getId());
      }
    }

    return deptids;
  }

  /** 获取所有父部门id */
  @Override
  public List<Integer> getParentDeptIds(Integer deptid) {
    Dept dept = deptMapper.selectById(deptid);
    String pids = dept.getPids();
    String[] split = pids.split(",");
    ArrayList<Integer> parentDeptIds = new ArrayList<>();
    for (String s : split) {
      parentDeptIds.add(Integer.valueOf(StrKit.removeSuffix(StrKit.removePrefix(s, "["), "]")));
    }
    return parentDeptIds;
  }
}
